#include "downloadtabledelegate.h"
#include <QProgressBar>
#include <QPainter>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QApplication>
#include "priorityqueue.h"
#include "downloadtable.h"

DownloadTableDelegate::DownloadTableDelegate(QObject *parent) :
    QItemDelegate(parent)
{
}

void DownloadTableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const
{
    switch(index.column()){
        case 2:
            progressBarPaint(painter, option, index);
            break;
        case 3:
            priorityIconPaint(painter, option, index);
            break;
        default:
            QItemDelegate::paint(painter, option, index);
            break;
    }
}

void DownloadTableDelegate::progressBarPaint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const {
    QStyleOptionProgressBar progressBarOption;
    progressBarOption.state = QStyle::State_Enabled;
    progressBarOption.direction = QApplication::layoutDirection();
    progressBarOption.rect = option.rect;
    progressBarOption.fontMetrics = QApplication::fontMetrics();
    progressBarOption.minimum = 0;
    progressBarOption.maximum = 100;
    progressBarOption.textAlignment = Qt::AlignCenter;
    progressBarOption.textVisible = true;

    int progress = qobject_cast<DownloadTable *>(parent())->progressForTask(index.row());
    progressBarOption.progress = progress < 0 ? 0 : progress;
    progressBarOption.text = QString().sprintf("%d%%", progressBarOption.progress);

    QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
}

void DownloadTableDelegate::priorityIconPaint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const {
    QString filename;
    int x = option.rect.x() + option.rect.width()/2, y = option.rect.y();
    int priority = index.data().toInt();
    switch(priority){
        case 0:
            filename = ":/icons/low.png";
            x -= 16;
            break;
        case 1:
            filename = ":/icons/normal.png";
            x -= 32;
            break;
        case 2:
            filename = ":/icons/high.png";
            x -= 48;
            break;
    }

    QImage image(filename);
    painter->drawImage(x, y, image);
}
